This is an R Markdown Notebook. When you execute code within the notebook, the results appear beneath the code. \(\sqrt{x}\) Try executing this chunk by clicking the Run button within the chunk or by placing your cursor inside it and pressing Ctrl+Shift+Enter.
library(ggplot2)
#数据集必须是data.frame格式#
head(mtcars)
## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
#ggplot2画图,首先要定义数据和坐标,其它东西例如标题,颜色,形状用图层的方法慢慢往上加。
p <- ggplot(mtcars, aes(x=mpg, y=wt, colour=cyl))
p
#可以看到我们定义了横坐标为mpg,纵坐标为wt,颜色按照cyl分类。cyl在这里就相当于一个标签。也可以写成p <- ggplot(mtcars, aes(mpg, wt, colour=cyl))
p1 <- p+geom_point() #geom_point()为通过”+”以图层的方式加入点的几何对象,geom_point()表示点图
p1
#在geom_point()中,我们可以加入一些参数
p2 <- p+geom_point(color="blue")
p2
p3 <- p+geom_point(aes(color="blue"))#最后一行语句为错误的映射关系, 在aes中, color = “blue”的实际意思是把”blue”当为一个变量, 用这个变量里的数据去关联图形属性中的参数, 因为”blue”只含有一个字符变量, 默认情况下为离散变量, 按默认的颜色标度标记为桃红色
p3
pp <- ggplot(mtcars, aes(x = mpg, y = wt, color = factor(gear)))
#设定默认的映射关系,颜色改成离散型变量(不是渐变色了)
pp + geom_point()
#沿用默认的映射关系来绘制散点图
pp + geom_point(aes(shape = factor(carb)))
#添加图层中的shape的映射关系,点图中不同变量用不同的符号
pp + geom_point(aes(y = carb))
#修改默认的y的映射关系, 注意图中y轴名称仍然以默认的wt表示
pp + geom_point(aes(color = NULL))
#删除默认的color映射关系
p4 <- pp+geom_boxplot()#箱线图
p4
p5 <- pp+geom_boxplot(aes(fill=factor(gear)))#填充颜色
p5
library(ggplot2)
library(plotly)#引入新的R包可以做成可交互的数据可视化图
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
pp <- ggplot(mtcars, aes(x = mpg, y = wt, color = factor(gear)))
p3 <- pp +geom_point()
ggplotly(p3)
library(ggsci)#ggsci这个包可以按照期刊风格改变配色
p7 <-p3 +scale_color_npg()#nature系列配色
p7
pp+geom_boxplot()
p8 <- pp+geom_boxplot()+scale_color_npg()
p8
p9 <- pp + scale_color_aaas() +geom_boxplot()
p9
Add a new chunk by clicking the Insert Chunk button on the toolbar or by pressing Ctrl+Alt+I.
When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the Preview button or press Ctrl+Shift+K to preview the HTML file).
The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike Knit, Preview does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed.